// 存放所有本地数据
var allMenu = [];
var Menu = function(id, name, price, unit) {
	this.id = id;
	this.name = name;
	this.unitPrice = price;
	this.unit = unit;
}

var BillMenu = function(menu, count) {
	this.menu = menu;
	this.count = count;
	this.id = menu.id;
	this.name = menu.name;
	this.unitPrice = menu.unitPrice;
	this.unit = menu.unit;
}

var Bill = function() {
	this.init();
};
BillMenu.prototype = {
	reset : function(menu, count) {
		this.menu = menu;
		this.count = count;
		this.id = menu.id;
		this.name = menu.name;
		this.unitPrice = menu.unitPrice;
		this.unit = menu.unit;
	}
}

window.printBill = function(bill, callback) {
	cordova.exec(callback, callback, "PrintPlugin", "print", [bill]);
};
if (app.isWindowOS()) {
	window.printBill = function(bill, callback) {
		window.setTimeout(function() {
			callback({
				success : true,
				msg : '打印成功'
			});
		}, 2000);
	}
}

Bill.prototype = {
	totalPrice : null,
	tableName : '桌1',
	menuList : null,
	showDetail : function() {
		var template = $.createTemplateURL('templates/bill_info.html');
		var html = template.get(this);
		app.loadHTML(html, {
			transition : 'silde-left'
		});
	},
	showBillMenu : function(menuId, isBillPage) {
		if (window.event) {
			var el = window.event.target;
			if (el.tagName.toUpperCase() == 'INPUT') {
				return;
			}
		}
		var menu = this.getMenu(menuId);
		var template = $.createTemplateURL('templates/bill_menu.html');
		var count = this.getMenuCount(menuId);
		var billMenu = new BillMenu(menu, count);
		var value = "orderFood.show";
		if (isBillPage) {
			value = 'bill.showDetail'
		}
		template.setParam("callBack", value)
		var html = template.get(billMenu);
		app.loadHTML(html, {
			transition : 'silde-left'
		});

	},
	updateFoodNumber : function(menuId, countstr, callBack) {
		var count = parseInt(countstr);
		if (count == 0) {
			this.removeBill(menuId);
		} else {
			var menu = this.getMenu(menuId);
			var billMenu = this.getBillMenu(menuId);
			if (billMenu != null) {
				billMenu.reset(menu, count);
			} else {
				this.menuList.push(new BillMenu(menu, count))
			}
		}
		this.getTotalPrice();
		if ($.isFunction(callBack)) {
			callBack.call(this, []);
		}

	},
	toJson : function() {
		this.totalPrice = this.getTotalPrice();
		return JSON.stringify(this);
	},
	printData : function() {
		window.printBill(bill, function(result) {
			// 不加延迟会有问题.问题还未知
			window.setTimeout(app.unmask, 50);
			if (result) {
				if (bill.id == null) {
					bill.addBill(result.success);
				} else {
					bill.updateBill(result.success);
				}
				if (result.success == true) {
					alert(result.msg);
				} else {
					alert(result.msg);
				}
			} else {
				alert('已经调用打印功能,但没有返回消息');
			}
		});
	},
	print : function() {
		if (bill.menuList.length < 1) {
			alert('还未点菜,不能打印');
			return;
		}
		app.mask();
		window.setTimeout(bill.printData, 50);

	},
	init : function() {
		this.menuList = [];
		return this;
	},
	getMenu : function(menuId) {
		for (var i = 0; i < allMenu.length; i++) {
			if (allMenu[i].id == menuId) {
				return new Menu(allMenu[i].id, allMenu[i].name, allMenu[i].unit_price, allMenu[i].unit);
			}
		}
		return null;
	},
	removeBill : function(menuId) {
		var index = this.getBillMenuIndex(menuId);
		if (index != -1) {
			this.menuList.splice(index, 1);
		}
	},
	getBillMenu : function(menuId) {
		for (var i = 0; i < this.menuList.length; i++) {
			if (this.menuList[i].id == menuId) {
				return this.menuList[i];
			}
		}
		return null;
	},
	getMenuCount : function(menuId) {
		var billMenu = this.getBillMenu(menuId);
		if (billMenu) {
			return billMenu.count;
		}
		return 0;
	},
	getBillMenuIndex : function(menuId) {
		for (var i = 0; i < this.menuList.length; i++) {
			if (this.menuList[i].menu.id == menuId) {
				return i;
			}
		}
		return -1;
	},
	addBillMenu : function(data) {
		var menu = new Menu(data.id, data.name, data.unit_price, data.unit)
		var billMenu = this.getBillMenu(menu.id);
		if (billMenu == null) {
			this.menuList.push(new BillMenu(menu, 1))
		} else {
			billMenu.count = billMenu.count + 1;
		}

	},
	/**
	 * 直接加,不判断是否存在,bill_history调用
	 * 
	 * @param {}
	 *            data
	 */
	addBillMenuWithCount : function(data) {
		var menu = new Menu(data.id, data.name, data.unit_price, data.unit);
		this.menuList.push(new BillMenu(menu, data.count))
	},
	toggleMenu : function(data) {
		var index = this.getBillMenuIndex(data.id);
		if (index != -1) {
			this.menuList.splice(index, 1);
		} else {
			var menu = new Menu(data.id, data.name, data.unit_price, data.unit)
			this.menuList.push(new BillMenu(menu, 1))
		}
		this.getTotalPrice();
	},
	getTotalPrice : function() {
		var total = 0;
		for (var i = 0; i < this.menuList.length; i++) {
			var itemPrice = this.menuList[i].unitPrice * this.menuList[i].count;
			total += itemPrice;
		}
		this.totalPrice = total;
		return total;
	},
	addBill : function(printStatus) {
		console.log("call add bill");
		var me = this;
		var db = app.getDB();
		var sql = "insert into bill(table_name,total_price,send_time,print_status,print_time) values (?,?,?,?,?)";
		db.transaction(function(tx) {
			var now = new Date().getTime();
			tx.executeSql(sql, [me.tableName, me.getTotalPrice(), now, printStatus ? 1 : 0, now], function(tx, results) {
				if (!results.rowsAffected) {
					alert("生成单号未成功!");
					return false;
				}
				me.id = results.insertId;
				console.log("insert id:" + results.insertId);
				me.saveMenuList(db)
			});
		}, errorCB);
	},
	saveMenuList : function(db) {
		var me = this;
		var sql = "insert into bill_menu (name,unit,unit_price,count,menu_id,bill_id) values (?,?,?,?,?,?)"
		db.transaction(function(tx) {
			for (var i = 0; i < me.menuList.length; i++) {
				var billMenu = me.menuList[i];
				tx.executeSql(sql, [billMenu.name, billMenu.unit, billMenu.unitPrice, billMenu.count, billMenu.id, me.id], null, errorCB);
			}
		}, errorCB);
	},
	updateBill : function(printStatus) {
		var me = this;
		var db = app.getDB();
		db.transaction(function(tx) {
			var sql = "update bill set table_name=?,total_price=?,send_time=?,print_status=?,print_time=? where id = ?";
			tx.executeSql(sql, [me.tableName, me.getTotalPrice(), new Date(), printStatus ? 1 : 0, new Date(), me.id], null, errorCB);
			sql = "delete from bill_menu where bill_id =?"
			tx.executeSql(sql, [me.id], null, errorCB);
			sql = "insert into bill_menu (name,unit,unit_price,count,menu_id,bill_id) values (?,?,?,?,?,?)"
			for (var i = 0; i < me.menuList.length; i++) {
				var billMenu = me.menuList[i];
				tx.executeSql(sql, [billMenu.name, billMenu.unit, billMenu.unitPrice, billMenu.count, billMenu.id, me.id], null, errorCB);
			}
		}, errorCB);
	},
	setSummary : function(id, tableName, totalPrice, sendTime, printTime, status) {
		var me = this;
		me.id = id;
		me.totalPrice = totalPrice;
		me.tableName = tableName;
		me.sendTime = sendTime;
		me.printTime = printTime;
		me.status = status;
	},
	reset : function() {
		var me = this;
		me.menuList = [];
		me.id = null;
		me.totalPrice = null;
		me.tableName = null;
	}
};
var bill = new Bill();
